package com.ybkj.daijia.api.driver.v4;

import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.event.listener.zhuanxian.ZhuanxianMemberRebateEventListener;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverApplyService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverPaymentsRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.DriverTimeService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.ZhuancheService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 司机登录相关
 *
 * @author bo
 */
@Controller("DriverRebateControllerV4")
@RequestMapping(value = "driver/api/rest/v4")
public class DriverRebateController {

    private static final Logger logger = LoggerFactory.getLogger(DriverRebateController.class);

    @Autowired
    private DriverService driverService;
    @Autowired
    private DriverTimeService driverTimeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private ZhuancheService zhuancheService;
    @Autowired
    private ErrandService errandService;
    @Autowired
    private FreightService freightService;
    @Autowired
    private DriverLoginService driverLoginService;
    @Autowired
    private DriverApplyService driverApplyService;
    @Autowired
    private DriverPaymentsRecordService driverPaymentsRecordService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private PassengerApi passengerApi;
    @Autowired
    private ZhuanxianMemberRebateEventListener zhuanxianMemberRebateEventListener;

    @RequestMapping(value = "queryDriverRebate", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryDriverRebate(String employToken, Integer page, Integer limit) {
        logger.debug("employToken:{},page:{},limit:{}", employToken, page, limit);

        if (StringUtils.isBlank(employToken) || null == page || null == limit) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            Page<DriverPaymentsRecord> rebatePage = driverPaymentsRecordService
                .queryByEmploy(driver.getId(), DriverPaymentsRecord.RECHARGE_TYPE_REBATE, null,
                    null, null, page, limit);

            List<DriverPaymentsRecord> content = rebatePage.getContent();
            long totalElements = rebatePage.getTotalElements();

            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
            if (!CollectionUtils.isEmpty(content)) {
                for (DriverPaymentsRecord driverPaymentsRecord : content) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("happend", driverPaymentsRecord.getHappend());
                    map.put("money", driverPaymentsRecord.getMoney());
                    mapList.add(map);
                }
            }
            Pageable pageable = new PageRequest(page, limit);
            Page<Map<String, Object>> pageMap = new PageImpl<Map<String, Object>>(mapList, pageable,
                totalElements);

            BigDecimal totalMoney = driverPaymentsRecordService
                .sumRebateByEmployWithDate(driver.getId(), null, null);

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("page", pageMap);
            dataMap.put("totalMoney", totalMoney);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(dataMap);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver queryRebate error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /**
     * e家人奖励 查询 driverpaymentrecord 表 recordType = rebate的记录
     *
     * @param employToken
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping(value = "queryRebate", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryRebate(String employToken, Integer page, Integer limit) {
        logger.debug("employToken:{},page:{},limit:{}", employToken, page, limit);

        if (StringUtils.isBlank(employToken) || null == page || null == limit) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }
        DriverLogin driverLogin = null;
        if ("super".equals(employToken)) {
            driverLogin = new DriverLogin();
            driverLogin.setDriverId(30L);
            driverLogin.setDeathDate(new Date(System.currentTimeMillis() + 1000000L));
        } else {
            driverLogin = driverLoginService.selectByToken(employToken);
        }

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {

            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            Page<DriverPaymentsRecord> rebatePage = driverPaymentsRecordService
                .queryByEmployRecordTypes(driver.getId(), null, null, null, page, limit,
                    DriverPaymentsRecord.RECHARGE_TYPE_REBATE,
                    DriverPaymentsRecord.DELETE_TYPE_REBATE);

            List<DriverPaymentsRecord> content = rebatePage.getContent();
            long totalElements = rebatePage.getTotalElements();

            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
            Map<String, Map<String, Object>> orderMaps = new HashMap<>();
            if (!CollectionUtils.isEmpty(content)) {
                for (DriverPaymentsRecord driverPaymentsRecord : content) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("happend", driverPaymentsRecord.getHappend());
                    map.put("money", driverPaymentsRecord.getMoney());
                    String orderNumber = driverPaymentsRecord.getOrderNumber();
                    String phone = zhuanxianMemberRebateEventListener
                        .getPassengerPhoneFromDriverPaymentRecord(driverPaymentsRecord);
                    //专车专线都是一个解析方式
                    map.put("phone", phone);
                    if (orderNumber.startsWith("CJZX")) {
                        //城际专线
                    } else {
                        //专车未开提成
                    }
                    String recordType = driverPaymentsRecord.getRecordType();
                    if (recordType.equals(DriverPaymentsRecord.RECHARGE_TYPE_REBATE)) {
                        map.put("name", driver.getRealname());
                    } else if (recordType.equals(DriverPaymentsRecord.DELETE_TYPE_REBATE)) {
                        Result<Passenger> result = passengerApi
                            .findOnePassengerByPhone(phone, settingUtils.get());
                        if (null != result && result.isSuccess()) {
                            Passenger passenger = result.getResult();
                            if (null != passenger) {
                                Driver driverB = driverService
                                    .findByUsername(passenger.getIntroducer());
                                map.put("name", null == driverB ? "" : driverB.getRealname());
                            }
                        }
//                        String name = zhuanxianApi.getOrderByOrderNo(driverPaymentsRecord.getOrderNumber());
//                        map.put("introducer", null == name?"":name);
                    }
                    mapList.add(map);
                }
            }
            Pageable pageable = new PageRequest(page, limit);
            Page<Map<String, Object>> pageMap = new PageImpl<Map<String, Object>>(mapList, pageable,
                totalElements);

            BigDecimal totalMoney = driverPaymentsRecordService
                .sumRebateByEmployWithDate(driver.getId(), null, null);

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("page", pageMap);
            dataMap.put("totalMoney", totalMoney);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(dataMap);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver queryRebate error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /***
     * 查询司机的被介绍人 根据mc系统的passenger的introducer来
     * @param employToken
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping(value = "queryIntroducer", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryIntroducer(String employToken, Integer page, Integer limit) {
        logger.debug("employToken:{},page:{},limit:{}", employToken, page, limit);

        if (StringUtils.isBlank(employToken) || null == page || null == limit) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            Page<Map<String, Object>> passengerPage = memberService
                .queryByIntroducer(driver.getUsername(), Passenger.INTRODUCE_TYPE_DRIVER, page,
                    limit);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(passengerPage);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver queryIntroducer error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }


}
